package com.bjpowernode.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONUtil;
import com.bjpowernode.constant.Constants;
import com.bjpowernode.entity.TActivity;
import com.bjpowernode.entity.TUser;
import com.bjpowernode.mapper.TActivityMapper;
import com.bjpowernode.query.ActivityQuery;
import com.bjpowernode.service.ActivityService;
import com.bjpowernode.utils.JwtUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 */
@Service
public class ActivityServiceImpl implements ActivityService {

    @Resource
    private TActivityMapper tActivityMapper;

    @Resource
    private JwtUtil jwtUtil;
    @Override
    public PageInfo<TActivity> getActivityByPage(Integer current, ActivityQuery activityQuery) {
        // 开启分页
        PageHelper.startPage(current, Constants.PAGE_SIZE);
        // 查询
        List<TActivity> tActivityList = tActivityMapper.getAllActivity(activityQuery);
        // 封装
        PageInfo<TActivity> pageInfo = new PageInfo<>(tActivityList);
        // 返回
        return pageInfo;
    }

    @Override
    public int save(ActivityQuery activityQuery) {
        TActivity activity = new TActivity();
        BeanUtils.copyProperties(activityQuery, activity);
        // 创建时间
        activity.setCreateTime(DateTime.now());
        // 创建人
        // 解析jwt
        String parseToken = jwtUtil.parseToken(activityQuery.getJwt());
        TUser user = JSONUtil.toBean(parseToken, TUser.class);
        // 项目负责人
        activity.setOwnerId(user.getId());
        // 项目创建人
        activity.setCreateBy(user.getId());
        // 编辑时间
        activity.setEditTime(DateTime.now());
        // 编辑人
        activity.setEditBy(user.getId());
        int i = tActivityMapper.insertSelective(activity);
        return i;
    }

    @Override
    public TActivity getActivityById(Integer id) {
        TActivity tActivity = tActivityMapper.getActivityById(id);
        return tActivity;
    }

    @Override
    public int updataUserById(ActivityQuery activityQuery) {
        TActivity tActivity = new TActivity();
        // 复制
        BeanUtils.copyProperties(activityQuery, tActivity);
        // 获取编辑人
        String parseToken = jwtUtil.parseToken(activityQuery.getJwt());
        TUser user = JSONUtil.toBean(parseToken, TUser.class);
        tActivity.setEditBy(user.getId());
        // 设置更新时间
        tActivity.setEditTime(DateTime.now());
        int i = tActivityMapper.updateByPrimaryKeySelective(tActivity);
        return i;
    }

    @Override
    public int removeActivityById(Integer id) {
        return tActivityMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int batchDeleteActivitysByIds(List<Integer> idList) {
        int batch = tActivityMapper.batchDeleteByIds(idList);
        return batch;
    }
}
